package com.isunimp.sample.java.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Created by isunimp on 17/2/17.
 */
public class EchoServer {

    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(9999));
            serverSocketChannel.configureBlocking(false);

            while (true) {
                SocketChannel socketChannel = serverSocketChannel.accept();
                Socket socket = socketChannel.socket();
                SocketAddress remoteAddress = socket.getRemoteSocketAddress();
                System.out.println(remoteAddress);
                ByteBuffer buffer = ByteBuffer.allocate(100);
                buffer.clear();
                buffer.put("Hi! here is nio server.".getBytes());
                buffer.flip();// 写入通道之前必须加这一行设置为read模式
                socketChannel.write(buffer);
                socketChannel.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

}
